package popup

import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import android.widget.PopupWindow
import android.widget.TextView
import app.AppContext
import com.hontech.kdxclient.R
import event.DeliverCompleteEvent
import event.DeliveryResultEvent
import event.InventoryChangedEvent
import event.ReportEvent
import ext.log
import manager.AppManager
import manager.PayManager
import manager.TaskManager
import manager.WaresManager
import mvc.model.inventory.GoodsType
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import protocol.BaseProtocol
import serialport.DeliverPortManager
import task.ReportTask
import task.WebPushTask
import view.DeliveryView
import view.LoadImageView
import java.lang.Exception

class DeliveryWindow : Runnable {

    companion object {

        val Instance: DeliveryWindow by lazy { DeliveryWindow() }

        var isShow = false
        var isComplete = false
        var isReport = false
        private const val TIME_OUT = 120 * 1000
    }

    private var goodsType: GoodsType? = null
    private val view = LayoutInflater.from(AppContext).inflate(R.layout.popup_delivery, null)
    private val iconImageView = view.findViewById<LoadImageView>(R.id.id_delivery_image_view)
    private val deliveryView = view.findViewById<DeliveryView>(R.id.id_delivery_deliver_view)
    private val window =
        PopupWindow(view, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.MATCH_PARENT, true)
    private val textViewMessage = view.findViewById<TextView>(R.id.id_delivery_text_view_message)

    init {
        window.animationStyle = R.style.PayTheme
    }

    private fun cargoName(): String {
        return goodsType?.name ?: "Unknown"
    }

    private fun clearCargo() {
        if (!AppManager.CLEAR_CARGO_IF_FAIL) {
            return
        }

        if (goodsType == null) {
            return
        }

        goodsType!!.number = 0
        WaresManager.selectInfo.update()
        AppManager.setFaultByCargo(goodsType!!.name)
        EventBus.getDefault().post(InventoryChangedEvent())
    }

    private fun initUi() {
        EventBus.getDefault().register(this)
        val info = WaresManager.selectInfo
        iconImageView.setImageWithUrl(info.maxImageUrl)
        deliveryView.progress.maxValue = TIME_OUT.toFloat() / 1000
        deliveryView.progress.start()
        textViewMessage.text = "正在出货请稍后"
        delivery()
    }

    private fun delivery() {

        goodsType = null
        val info = WaresManager.selectInfo

        try {
            goodsType = info.firstGoodsType()
        } catch (e: Exception) {
            e.printStackTrace()
            onError("找不到货道")
            return
        }
        WaresManager.selectInfo.update()
        EventBus.getDefault().post(InventoryChangedEvent())
        TaskManager.DelayHandler.post(ReportTask(cargoName(), PayManager.CurrentOrder))
        val buf = BaseProtocol(0x04)
            .appendByte(goodsType!!.row)
            .appendByte(goodsType!!.col)
            .build()
        DeliverPortManager.Instance.write(buf)
    }

    private fun dismiss() {
        if (!isShow) {
            return
        }
        EventBus.getDefault().unregister(this)
        TaskManager.UiHandler.removeCallbacks(this)
        deliveryView.progress.cancel()
        window.dismiss()
        AppManager.isBusy = false
        isShow = false
    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onRepoerEvent(env: ReportEvent) {
        isReport = true
        if (isComplete) {
            dismiss()
        }
    }



    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    fun onDeliveryResuleEvent(env: DeliveryResultEvent) {
        /**
         *  0x00 -> return "出货成功"
            0x01 -> return "此货道无货"
            0x03 -> return "电机堵转"
            0x02 -> return "电机超时"
            0x04 -> return "无此货道"
            0x05 -> return "出货失败"
            0x06 -> return "光栅被遮挡,无法出货"
            0x07 -> return "电机其他故障"
            0x08 -> return "出货失败但客户没有及时取走货物"
            0x09 -> return "第二/三次开门成功"
            0x0A -> return "第二/三次关门但客户未及时取走货物"
            0x0B -> return "第一/二/三次关门并且客户取走货物"
            else -> return "未知异常"
         */

        when (env.state) {
            0x00 -> {
                onSuccess()
            }
            0x01 -> { // 这个货道没有货
                log("此货道无货")
                clearCargo()
                delivery()
            }
            0x04, 0x05, 0x0C -> {
                clearCargo()
                onError("出货失败:${env.state}")
            }
            0x08, 0x0B, 0x0A -> {
                onComplete()
            }
        }
    }

    private fun onComplete() {
        isComplete = true
        if (isReport) {
            dismiss()
        }
    }

    private fun onError(msg: String) {
        log("出货失败", "出货")
        TaskManager.UiHandler.removeCallbacks(this)
        deliveryView.progress.cancel()
        textViewMessage.text = "出货失败 将于24小时内退款"
        PayManager.refund(PayManager.CurrentOrder, cargoName(), "出货失败退款 $msg")
        TaskManager.UiHandler.postDelayed({
            dismiss()
        }, 2000)
    }

    private fun onSuccess() {
        log("出货成功", "出货")
        TaskManager.UiHandler.removeCallbacks(this)
        deliveryView.progress.cancel()
        textViewMessage.text = "出货成功 请从下方取物口取走商品"
        EventBus.getDefault().post( DeliverCompleteEvent() )
    }

    override fun run() {
        log("出货超时", "出货")
        PayManager.refund(PayManager.CurrentOrder, cargoName(), "出货超时退款")
       // TaskManager.DelayHandler.post(WebPushTask("Error"))
        dismiss()
    }

    fun show(view: View) {
        if (isShow) {
            return
        }
        AppManager.isBusy = true
        isShow = true
        isReport = false
        isComplete = false
        window.showAtLocation(view, Gravity.CENTER, 0, 0)
        TaskManager.UiHandler.postDelayed(this, TIME_OUT.toLong())
        initUi()
    }
}